      //
//  SNKHeadNewsController.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/8.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//


#import <DKNightVersion/DKNightVersion.h>
#import <MJExtension.h>
#import "MJRefresh.h"
#import <SDCycleScrollView.h>
#import "MBProgressHUD+Extion.h"

#import "KDJHttpTool.h"
#import <PPNetworkHelper.h>

#import "SNKDataModel.h"
#import "SNKBannerData.h"

#import "SNKNewsCell.h"
#import "SNKImagesCell.h"
#import "SNKTopImageCell.h"

#import "SNKHeadNewsController.h"
#import "GYHHeadeRefreshController.h"
#import "SNKBannerViewController.h"
#import "SNKDetailWebController.h"

@interface SNKHeadNewsController() <UITableViewDelegate, UITableViewDataSource, SDCycleScrollViewDelegate>

@property (nonatomic , strong) UITableView *myTableView;
@property (nonatomic , assign) NSInteger currentPage;
@property (nonatomic , strong) NSMutableArray *totalArray;
@property (nonatomic , strong) NSMutableArray *bannerArray;
@property (nonatomic , strong) SDCycleScrollView *cycleScrollView;

@end

@implementation SNKHeadNewsController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 监听二次点击刷新
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(mynotification) name:@"新闻" object:nil];
    
    // 添加CycleView
    self.myTableView.tableHeaderView = self.cycleScrollView;
    
    // 添加tableView
    [self.view addSubview:self.myTableView];
    
    // 加载数据
    [self loadBannerData];
    [self.myTableView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)mynotification
{
    [self.myTableView.mj_header beginRefreshing];
}

#pragma mark - SDCycleScrollViewDelegate
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index {
    SNKBannerViewController *bannerVc = [[SNKBannerViewController alloc] init];
    bannerVc.url = [self targetUrlStringWithIndex:index];
    [self.navigationController pushViewController:bannerVc animated:YES];
}

- (NSString *)targetUrlStringWithIndex:(NSInteger)index {
    
    SNKBannerData *data = self.bannerArray[index];
    NSString *url1 = [data.url substringFromIndex:4];
    url1 = [url1 substringToIndex:4];
    NSString *url2 = [data.url substringFromIndex:9];
    url2 = [NSString stringWithFormat:@"http://c.3g.163.com/photo/api/set/%@/%@.json",url1,url2];
    
    return url2;
}

#pragma mark - tableView DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.totalArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SNKDataModel *newsModel = self.totalArray[indexPath.row];
    NSString *ID = [SNKNewsCell idForRow:newsModel];
    KLog(@"%@", ID);
    if ([ID isEqualToString:@"kImagesCell"]){
        
        SNKImagesCell *cell = [SNKImagesCell cellWithTableView:tableView];
        // 颜色相关
        cell.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
        cell.dataModel = newsModel;
        return cell;
    } else if ([ID isEqualToString:@"kNewsCell"]) {
        
        SNKNewsCell *cell = [SNKNewsCell cellWithTableView:tableView];
        // 颜色相关
        cell.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
        cell.dataModel = newsModel;
        return cell;
        
    } else {
    
        SNKTopImageCell *cell = [SNKTopImageCell cellWithTableView:tableView];
        // 颜色相关
        cell.dk_backgroundColorPicker = DKColorPickerWithKey(BAR);
        return cell;
    }

}

#pragma mark - TableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    SNKDataModel *newsModel = self.totalArray[indexPath.row];
    CGFloat rowHeight = [SNKNewsCell heightForRow:newsModel];
    return rowHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SNKDataModel *data = self.totalArray[indexPath.row];
    
    NSString *ID = [SNKNewsCell idForRow:data];
    if ([ID isEqualToString:@"kImagesCell"] && data.photosetID) { // 必须同时有photoSet才显示 banner
        
        NSString *url1 = [data.photosetID substringFromIndex:4];
        url1 = [url1 substringToIndex:4];
        NSString *url2 = [data.photosetID substringFromIndex:9];
        KLog(@"%@, %@", url1, url2)
        
        url2 = [NSString stringWithFormat:@"http://c.3g.163.com/photo/api/set/%@/%@.json",url1,url2];
        SNKBannerViewController *bannerVC = [[SNKBannerViewController alloc] init];
        bannerVC.url = url2;
        [self.navigationController pushViewController:bannerVC animated:YES];
        
    } else {
        SNKDetailWebController *detailVC = [[SNKDetailWebController alloc] init];
        detailVC.dataModel = self.totalArray[indexPath.row];
        detailVC.view.backgroundColor = [UIColor whiteColor];
        [self.navigationController pushViewController:detailVC animated:YES];
    }
    
}

#pragma mark - 网络请求

// 下拉,刷新数据
- (void)requestNewData {
    // 清零
    self.currentPage = 0;
    [_totalArray removeAllObjects];
    [self getTableViewData];
}

// 上拉,加载更多旧数据
- (void)requestMoreData {
    self.currentPage ++;
    [self getTableViewData];
}

- (void)getTableViewData {
    IMP_BLOCK_SELF(SNKHeadNewsController);
    
    NSString *urlStr = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/headline/T1348647853363/%ld-20.html",(long)self.currentPage * 20];
    
    [PPNetworkHelper GET:urlStr parameters:nil responseCache:^(id responseCache) {
        if (![PPNetworkHelper isNetwork]) {
            NSArray *dictArray = responseCache[@"T1348647853363"];
            NSArray *arrayM = [SNKDataModel mj_objectArrayWithKeyValuesArray:dictArray];
            NSMutableArray *statusArray = [NSMutableArray array];
            for (SNKDataModel *data in arrayM) {
                [statusArray addObject:data];
            }
            
            [block_self.totalArray addObjectsFromArray:statusArray];
            
            [block_self.myTableView reloadData];
            [block_self.myTableView.mj_header endRefreshing];
            [block_self.myTableView.mj_footer endRefreshing];
        }
    } success:^(id responseObject) {
        NSArray *dictArray = responseObject[@"T1348647853363"];
        NSArray *arrayM = [SNKDataModel mj_objectArrayWithKeyValuesArray:dictArray];
        NSMutableArray *statusArray = [NSMutableArray array];
        for (SNKDataModel *data in arrayM) {
            [statusArray addObject:data];
        }
        
        [block_self.totalArray addObjectsFromArray:statusArray];
        
        [block_self.myTableView reloadData];
        [block_self.myTableView.mj_header endRefreshing];
        [block_self.myTableView.mj_footer endRefreshing];
    } failure:^(NSError *error) {
        [block_self.myTableView.mj_header endRefreshing];
        [block_self.myTableView.mj_footer endRefreshing];
    }];
}

- (void)loadBannerData
{
    // 头条请求URL
    NSString *cycleNewsRequestURL = @"http://c.m.163.com/nc/article/headline/T1348647853363/0-10.html";
    
    IMP_BLOCK_SELF(SNKHeadNewsController);
    
    [PPNetworkHelper GET:cycleNewsRequestURL parameters:nil responseCache:^(id responseCache) {
        if (![PPNetworkHelper isNetwork]) {
            // 直接取出ads
            NSArray *dataArray = [SNKBannerData mj_objectArrayWithKeyValuesArray:responseCache[@"T1348647853363"][0][@"ads"]];
            
            NSMutableArray *tempImagesArray = [NSMutableArray array];
            NSMutableArray *tempTitlesArray = [NSMutableArray array];
            for (SNKBannerData *adObject in dataArray) {
                [block_self.bannerArray addObject:adObject];
                [tempImagesArray addObject:adObject.imgsrc];
                [tempTitlesArray addObject:adObject.title];
            }
            
            block_self.cycleScrollView.localizationImageNamesGroup = tempImagesArray;
            block_self.cycleScrollView.titlesGroup = tempTitlesArray;
        }
    } success:^(id responseObject) {
        // 直接取出ads
        NSArray *dataArray = [SNKBannerData mj_objectArrayWithKeyValuesArray:responseObject[@"T1348647853363"][0][@"ads"]];
        
        NSMutableArray *tempImagesArray = [NSMutableArray array];
        NSMutableArray *tempTitlesArray = [NSMutableArray array];
        for (SNKBannerData *adObject in dataArray) {
            [block_self.bannerArray addObject:adObject];
            [tempImagesArray addObject:adObject.imgsrc];
            [tempTitlesArray addObject:adObject.title];
        }
        
        block_self.cycleScrollView.localizationImageNamesGroup = tempImagesArray;
        block_self.cycleScrollView.titlesGroup = tempTitlesArray;
    } failure:^(NSError *error) {
        
    }];
    
}

#pragma mark - Getter and Setter

- (UITableView *)myTableView {
    IMP_BLOCK_SELF(SNKHeadNewsController);
    
    if (_myTableView == nil) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH -  64 - 49)];
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        
        // 夜间模式颜色
        _myTableView.dk_backgroundColorPicker = DKColorPickerWithKey(SEP);
        
        // 设置下拉控件
        GYHHeadeRefreshController *header = [GYHHeadeRefreshController headerWithRefreshingBlock:^{
            [block_self requestNewData]; // 下拉
        }];
        header.lastUpdatedTimeLabel.hidden = YES;
        header.stateLabel.hidden = YES;
        _myTableView.mj_header = header;
        
        // 设置上拉控件
        _myTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            [block_self requestMoreData]; // 上拉
        }];
    }
    return _myTableView;
}

- (NSMutableArray *)totalArray
{
    if (!_totalArray) {
        _totalArray = [NSMutableArray array];
    }
    return _totalArray;
}

- (NSMutableArray *)bannerArray {
    if (!_bannerArray) {
        _bannerArray = [NSMutableArray array];
    }
    return _bannerArray;
}

- (SDCycleScrollView *)cycleScrollView {
    if (_cycleScrollView == nil) {
        _cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 100, SCREENW, SCREENW * 0.5) delegate:self placeholderImage:[UIImage imageNamed:@"shadow.png"]];
        _cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        _cycleScrollView.pageControlStyle = SDCycleScrollViewPageContolStyleAnimated;
    }
    return _cycleScrollView;
}

@end
